<template>
  <div>
    <i-page-header class="product_tabs" :title="$route.meta.title">
    </i-page-header>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Form ref="formValidate" :model="formValidate">
        <Row type="flex" :gutter="24">
          <Col v-bind="grid">
            <FormItem label="搜索：" label-for="status2">
              <Input
                search
                enter-button
                placeholder="请输入名称"
                v-model="formValidate.title"
                @on-search="userSearchs"
              />
            </FormItem>
          </Col>
        </Row>
        <Row type="flex">
          <Col v-bind="grid">
            <Button type="primary" @click="tapAdd" icon="md-add"
              >添加数据</Button
            >
          </Col>
        </Row>
      </Form>

      <Table
        :columns="columns1"
        :data="tableData"
        class="mt25"
        no-userFrom-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
        :loading="loading"
        highlight-row
      >
        <template slot-scope="{ row }" slot="imgs">
          <div
            style="
              max-width: 96px;
              max-height: 35px;
              overflow: hidden;
              text-align: center;
            "
            v-if="row.media_type == 'img'"
          >
            <img
              v-image-preview
              style="max-width: 96px; max-height: 35px; cursor: pointer"
              :src="row.img"
            />
          </div>
          <div v-if="row.media_type == 'video'">
            <div class="video-img" @click="tapOpenVideo(row.video_data)">
              <img :src="row.video_data.img" />
              <div class="video-open fx-h fx-ac fx-bc">
                <Icon type="logo-youtube" />
                <div style="font-size: 12px; display: none">
                  时间:{{ $utils.getTimeVal(row.video_data.play_time) }}/{{
                    $utils.getFileSize(row.video_data.size)
                  }}
                </div>
              </div>
            </div>
          </div>
        </template>

        <template slot-scope="{ row }" slot="data">
          <div v-for="item in row.jsonAr" :key="item">
            {{ item.name }}：
            <span v-for="item2 in item.selectAr" :key="item2">
              <span v-if="item2.value == item[item.code]">
                {{ item2.text }}
              </span>
            </span>
          </div>
        </template>

        <template slot-scope="{ row }" slot="status">
          <el-tag v-if="row.is_show == 1">开启</el-tag>
          <el-tag type="info" v-else>关闭</el-tag>
        </template>
        <template slot-scope="{ row }" slot="action">
          <a @click="tapEdit(row.id)">编辑</a>
          <Divider type="vertical" />
          <a @click="tapDel(row)">删除</a>
        </template>

        <template slot-scope="{ row }" slot="media_type">
          <div v-if="row.media_type == 'img'">图片</div>
          <div v-if="row.media_type == 'video'">视频</div>
        </template>

        <template slot-scope="{ row }" slot="img">
          <el-avatar icon="el-icon-user-solid" :src="row.img"></el-avatar>
        </template>
      </Table>

      <div class="acea-row row-right page">
        <Page
          :total="page.count"
          show-elevator
          show-total
          @on-change="tapPage"
          :page-size="page.pageSize"
        />
      </div>
    </Card>

    <Modal v-model="dialogVisible" :title="title" @on-cancel="editClose">
      <el-form ref="form" :model="form" label-width="120px">
        <div class="alert-tip" :class="isAlert ? 'show' : ''">
          <div v-html="$utils.RichText(sys.adver_text)"></div>
          <div class="show-tip" @click="isAlert = !isAlert">
            {{ isAlert ? '隐藏' : '显示' }}
          </div>
        </div>

        <el-form-item
          label="标题"
          prop="title"
          :rules="[{ required: true, message: '请输入标题' }]"
        >
          <el-input
            placeholder="请输入标题"
            autocomplete="off"
            v-model="form.title"
          ></el-input>
        </el-form-item>

        <el-form-item label="类型" style="margin-bottom: 0">
          <el-radio-group v-model="form.media_type">
            <el-radio label="img">图片模式</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="form.media_type == 'img' && adverPageOne.type == 1"
          label="图片"
          prop="img"
          :rules="[{ required: true, message: '请上传图片' }]"
        >
          <ui-upload
            :upUrl="upUrl"
            :img="form.img"
            fileName="图片"
            :headers="upHeaders"
            :updata="{ isz: 0 }"
            @onUpload="onUpload"
          ></ui-upload>
        </el-form-item>

        <el-form-item
          v-if="form.media_type == 'video' && adverPageOne.type == 1"
          label="视频"
          prop="video_url"
          :rules="[{ required: true, message: '请上传视频' }]"
        >
          <ui-uploadmp4
            ref="fileupdate"
            :video_data="form.video_data"
            :upUrl="videoUrl"
            :headers="upHeaders"
            tip="视频大小，大小不超过500MB，上传视频尽量在闲时间上传，会影响服务器带宽和CPU资源！"
            @onUpload="onePackageSuccess"
          ></ui-uploadmp4>
        </el-form-item>

        <el-form-item label="其他说明">
          <div v-for="item in headeAr" :key="item.id">
            <el-tag v-if="item.mono != ''">{{
              $utils.RichText(item.mono)
            }}</el-tag>
          </div>
        </el-form-item>

        <div v-for="(item, index) in dataAr" :key="index">
          <el-form-item :prop="item.code" :label="item.name">
            <Select v-if="item.type == 'select'" v-model="item[item.code]">
              <Option
                v-for="item2 in item.selectAr"
                :value="item2.value"
                :key="item2.value"
                >{{ item2.text }}</Option
              >
            </Select>
            <el-input
              v-if="item.type == 'text'"
              v-model="item[item.code]"
              :placeholder="'请输入' + item.name"
            ></el-input>

            <el-input
              type="textarea"
              rows="5"
              v-if="item.type == 'textarea'"
              v-model="item[item.code]"
              :placeholder="'请输入' + item.name"
            ></el-input>
          </el-form-item>
        </div>

        <el-form-item
          label="内容"
          prop="text"
          :rules="[{ required: true, message: '请输入内容' }]"
          v-if="adverPageOne.type == 2"
        >
          <el-input
            type="textarea"
            placeholder="请输入内容"
            autocomplete="off"
            v-model="form.text"
          ></el-input>
        </el-form-item>

        <el-form-item label="链接参数">
          <el-input
            placeholder="请输入链接参数"
            autocomplete="off"
            v-model="form.url"
          ></el-input>
        </el-form-item>

        <el-form-item label="排序">
          <el-input placeholder="排序越高越前面" v-model="form.sort"></el-input>
        </el-form-item>

        <el-form-item label="是否显示" style="margin-bottom: 0">
          <el-radio-group v-model="form.is_show">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subAdmin">确 定</el-button>
      </span>
    </Modal>
  </div>
</template>

<script>
import IPageHeader from '@/layouts/system/page-header/index'
import { mapState, mapActions } from 'vuex'
import UiUpload from '@/ui/upload/index'
import Setting from '@/setting'
import util from '@/libs/util'
import {
  SystemAdverPage,
  SystemAdverPageTree,
  SystemAdverUpdate,
  SystemAdver,
  SystemAdverInfo,
  SystemAdverDel,
} from '../../../api/system/adver'
import UiUploadmp4 from '../../../ui/upload/ui-uploadmp4'
export default {
  name: 'system_adver',
  components: { UiUploadmp4, UiUpload, IPageHeader },
  computed: {},
  data() {
    return {
      title: '添加幻灯片',
      dialogVisible: false,
      isAlert: false,
      upHeaders: [],
      upUrl: '',
      videoUrl: '',
      grid: {
        xl: 7,
        lg: 7,
        md: 12,
        sm: 24,
        xs: 24,
      },
      artType: 'all',
      sys: {},
      headeAr: [],
      headrIndex: 0,
      headrIndex2: 0,
      adverPageOne: {},
      columns1: [
        {
          title: '标题',
          key: 'title',
          minWidth: 150,
        },
        {
          title: '图片',
          key: 'img',
          slot: 'imgs',
          minWidth: 150,
        },
        {
          title: '类型',
          slot: 'media_type',
          minWidth: 180,
        },
        {
          title: '分类',
          key: 'cate_name',
          minWidth: 180,
        },

        {
          title: '链接地址',
          key: 'url',
          minWidth: 150,
        },

        {
          title: '数据属性',
          key: 'data',
          slot: 'data',
          minWidth: 150,
        },

        {
          title: '发布时间',
          key: 'time',
          minWidth: 150,
        },
        {
          title: '排序',
          key: 'sort',
          minWidth: 100,
          fixed: 'right',
        },
        {
          title: '状态',
          key: 'status',
          slot: 'status',
          minWidth: 100,
          fixed: 'right',
        },
        {
          title: '操作',
          key: 'action',
          slot: 'action',
          fixed: 'right',
          minWidth: 120,
        },
      ],
      loading: true,
      tableData: [],
      page: {
        count: 0, //一共多少数量
        pageSize: 0, //每一页码数量
        page: 1, //当前页码
      },
      formValidate: { title: '' },
      form: {
        title: '',
        text: '',
        url: '',
        img: '',
        sort: 0,
        is_show: 1,
        page_id: 0,
        media_type: 'img',
        video_data: [],
      },
      dataAr: [],
    }
  },
  props: {
    page_id: {
      default: '',
      type: String,
    },
    // 开启后，链接颜色为默认的蓝色，默认关闭为继承效果
    linkColor: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    this.initView()
  },
  methods: {
    initView: function () {
      var upHeaders = {}
      this.upUrl = Setting.apiBaseURL + '/systemv1/upload/index'
      this.videoUrl = Setting.apiBaseURL + '/systemv1/upload/mp4'
      const token = this.$utils.util.cookies.get('system_token')
      if (token) {
        upHeaders['SYSTEM-ACC-TOKEN'] = token
      }
      this.upHeaders = upHeaders
      this.getAdverPage()
    },

    getAdverPage: function () {
      this.$utils.loading(this, '获取数据中...')
      //SystemAdverPageTree(),SystemAdverPage(),
      var PromiseAll = [SystemAdverPage({ id: this.page_id })]
      Promise.all(PromiseAll)
        .then((res) => {
          this.$utils.loadingClose()
          this.headeAr = res[0].data
          this.tableData = []
          this.getData()
        })
        .catch((err) => {
          console.log(err)
          this.$utils.loadingClose()
          this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
        })
    },

    /**
     * 获取数据
     */
    getData: function () {
      var data = {
        title: this.formValidate.title,
        page: this.page.page,
        page_id: this.page_id,
      }
      SystemAdver(data)
        .then((res) => {
          this.loading = false
          if (res.code == 200) {
            this.tableData = res.data.list
            this.page.pageSize = res.data.pageSize
            this.page.count = res.data.pageCount
          } else {
            this.$alert(res.msg)
          }
        })
        .catch((err) => {
          console.log(err)
          this.loading = false
          this.$utils.loadingClose()
          this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
        })
    },
    userSearchs() {
      this.page.page = 1
      this.loading = true
      this.getData()
    },
    //关闭
    editClose: function () {
      this.dialogVisible = false
    },
    /**
     * 添加广告栏目
     */
    tapAdd: function (sassid) {
      this.title = '添加广告'
      this.dialogVisible = true
      var data = this.headeAr[this.headrIndex]
      this.dataAr = data.json == '' ? [] : JSON.parse(data.json)
      this.adverPageOne = data
      this.$refs['form'].resetFields()
      this.form = this.$utils.resetFields(this.form, {
        page_id: data.id,
        is_show: 1,
        media_type: 'img',
        video_data: [],
      })
    },

    /**
     * 修改分页
     */
    tapEdit: function (id) {
      this.$utils.loading(this, '获取数据中...')
      SystemAdverInfo({ id: id })
        .then((res) => {
          this.$utils.loadingClose()
          if (res.code == 200) {
            this.form = res.data
            var pageData = this.headeAr[0]
            //循环page
            if (pageData != null) {
              var jsonData =
                pageData.json == '' ? [] : JSON.parse(pageData.json)
              var json2Data =
                res.data.data == '' ? [] : JSON.parse(res.data.data)
              for (var ii in jsonData) {
                for (var i in json2Data) {
                  if (json2Data[i].code == jsonData[ii].code) {
                    jsonData[ii][jsonData[ii].code] =
                      json2Data[i][jsonData[ii].code]
                  }
                }
              }
            }
            this.adverPageOne = pageData
            this.dataAr = jsonData
            this.dialogVisible = true
            this.title = '修改内容'
          } else {
            this.$alert(res.msg)
          }
        })
        .catch((err) => {
          this.$utils.loadingClose()
          this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
        })
    },
    /**
     * 分页
     */
    tapPage: function (index) {
      this.page.page = index
      this.getData()
    },
    /**
     * 修改数据
     */
    subAdmin: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let loading = this.$loading('提交数据中...')
          var data = {}
          for (var i in this.form) {
            data[i] = this.form[i]
          }
          data['data'] = JSON.stringify(this.dataAr)
          SystemAdverUpdate(data)
            .then((res) => {
              loading.close()
              if (res.code == 200) {
                this.dialogVisible = false
                this.$Message.success('操作成功')
                this.getData()
              } else {
                this.$alert(res.msg, '系统提示')
              }
            })
            .catch((err) => {
              loading.close()
              this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
            })
        }
      })
    },
    /**
     * 上传文件
     * @param res
     */
    onUpload: function (res) {
      if (res.code == -1) {
        Notice.error({ title: '系统提示', content: res.msg })
      } else {
        this.form.img = res.data.img
      }
    },
    // 删除
    tapDel(row) {
      this.$confirm('此操作将永久删除该栏目分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$utils.loading(this, '删除数据中...')
        SystemAdverDel({ id: row.id })
          .then((res) => {
            this.$utils.loadingClose()
            this.loading = true
            if (res.code == 200) {
              this.getData()
            } else {
              this.$alert(res.msg)
            }
          })
          .catch((err) => {
            this.$utils.loadingClose()
            this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
          })
      })
    },
  },
}
</script>
<style scoped>
.platform-img {
  width: 20px;
  height: 20px;
  background: #f2f2f2;
  margin-right: 4px;
}
.platform-img img {
  width: 100%;
}
.alert-tip {
  background-color: #f0f9eb;
  position: relative;
  height: 26px;
  overflow-y: hidden;
  color: #67c23a;
  padding: 8px 16px;
  border-radius: 4px;
  align-items: center;
  margin-bottom: 10px;
  font-size: 12px;
}
.show-tip {
  position: absolute;
  top: 5px;
  right: 5px;
  cursor: pointer;
}
.alert-tip.show {
  height: auto;
  overflow-y: auto;
}
.video-img {
  position: relative;
  display: inline-block;
  width: 96px;
  height: 35px;
  overflow: hidden;
  border-radius: 4px;
}
.video-img img {
  vertical-align: middle;
  border-radius: 4px;
  width: 100%;
}
.video-open {
  cursor: pointer;
  font-size: 20px;
  color: #fff;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 4px;
}
</style>
